<?php

namespace app\admin\model\scanwork;

use think\Model;

class QualityRecord extends Model
{
    // 表名
    protected $name = 'scanwork_quality_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'overall_result_text',
        'handle_method_text',
    ];
    
    public function getOverallResultList()
    {
        return ['1' => __('合格'), '2' => __('不合格'), '3' => __('让步接收')];
    }

    public function getOverallResultTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['overall_result']) ? $data['overall_result'] : '');
        $list = $this->getOverallResultList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getHandleMethodList()
    {
        return ['1' => __('返工'), '2' => __('报废'), '3' => __('让步接收')];
    }

    public function getHandleMethodTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['handle_method']) ? $data['handle_method'] : '');
        $list = $this->getHandleMethodList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 关联报工记录
    public function report()
    {
        return $this->belongsTo('app\admin\model\scanwork\Report', 'report_id', 'id');
    }

    // 通过报工记录关联小工单计划
    public function allocation()
    {
        return $this->hasOneThrough(
            'app\admin\model\scanwork\Allocation',
            'app\admin\model\scanwork\Report',
            'id', // 报工表的主键
            'id', // 小工单表的主键
            'report_id', // 质检记录表的外键
            'allocation_id' // 报工表的外键
        );
    }

    // 关联质检标准
    public function standard()
    {
        return $this->belongsTo('app\admin\model\scanwork\QualityStandard', 'standard_id', 'id');
    }

    // 关联质检员
    public function qualityUser()
    {
        return $this->belongsTo('app\common\model\User', 'quality_user_id', 'id');
    }

    // 关联质检图片
    public function images()
    {
        return $this->hasMany('app\admin\model\scanwork\QualityImage', 'record_id', 'id');
    }

    /**
     * 获取检查结果数组
     */
    public function getCheckResultsArray()
    {
        $checkResults = $this->check_results;
        if (is_string($checkResults)) {
            return json_decode($checkResults, true);
        }
        return $checkResults ?: [];
    }

    /**
     * 获取不合格项目数组
     */
    public function getUnqualifiedItemsArray()
    {
        $unqualifiedItems = $this->unqualified_items;
        if (is_string($unqualifiedItems)) {
            return json_decode($unqualifiedItems, true);
        }
        return $unqualifiedItems ?: [];
    }

    /**
     * 获取不合格原因数组
     */
    public function getUnqualifiedReasonsArray()
    {
        $unqualifiedReasons = $this->unqualified_reasons;
        if (is_string($unqualifiedReasons)) {
            return json_decode($unqualifiedReasons, true);
        }
        return $unqualifiedReasons ?: [];
    }

    /**
     * 计算总体结果
     */
    public function calculateOverallResult($checkResults)
    {
        if (!is_array($checkResults)) {
            return 2; // 默认不合格
        }

        $hasUnqualified = false;
        $hasQualified = false;

        foreach ($checkResults as $category => $items) {
            if (is_array($items)) {
                foreach ($items as $item => $result) {
                    if ($result === '不合格' || $result === '有缺陷' || $result === '有毛刺' || $result === '有划痕' || $result === '有变形') {
                        $hasUnqualified = true;
                    } elseif ($result === '合格' || $result === '无' || $result === '无缺陷' || $result === '无毛刺' || $result === '无划痕' || $result === '无变形') {
                        $hasQualified = true;
                    }
                }
            }
        }

        if ($hasUnqualified) {
            return 2; // 不合格
        } elseif ($hasQualified) {
            return 1; // 合格
        } else {
            return 2; // 默认不合格
        }
    }

    /**
     * 获取不合格项目
     */
    public function getUnqualifiedItems($checkResults)
    {
        $unqualifiedItems = [];
        
        if (!is_array($checkResults)) {
            return $unqualifiedItems;
        }

        foreach ($checkResults as $category => $items) {
            if (is_array($items)) {
                foreach ($items as $item => $result) {
                    if ($result === '不合格' || $result === '有缺陷' || $result === '有毛刺' || $result === '有划痕' || $result === '有变形') {
                        $unqualifiedItems[] = [
                            '项目' => $category . '-' . $item,
                            '问题' => $result,
                            '严重程度' => $this->getSeverityLevel($result)
                        ];
                    }
                }
            }
        }

        return $unqualifiedItems;
    }

    /**
     * 获取严重程度
     */
    private function getSeverityLevel($result)
    {
        $severeResults = ['不合格', '有缺陷', '有变形'];
        $moderateResults = ['有毛刺', '有划痕'];
        
        if (in_array($result, $severeResults)) {
            return '严重';
        } elseif (in_array($result, $moderateResults)) {
            return '中等';
        } else {
            return '轻微';
        }
    }
}
